#include "sock.hpp"
#include <poll.h>

namespace my_poll
{
  class Poll 
  {
    private:
      unsigned short port;
      int listen_sock;
    public:
      Poll(unsigned short _port):port(_port)
    {}
      ~Poll()
      {}

      void InitPoll()
      {
        listen_sock=my_sock::Sock::Socket();
        my_sock::Sock::Bind(listen_sock,port);
        my_sock::Sock::Listen(listen_sock,5);
      }
      void Run()
      {
        struct pollfd rfds[64];//初始化事件数组 为无效-1
        for(int i=0;i<64;i++)
        {
          rfds[i].fd=-1;
          rfds[i].events=0;
          rfds[i].revents=0;
        }
        rfds[0].fd=listen_sock;
        rfds[0].events |= POLLIN;
        rfds[0].revents=0;
      for(;;)
      {
        switch(poll(rfds,64,1000) )
        {
        case 0:
          std::cout<<" 等待时间结束..."<<std::endl;
          break;
        case -1:
          std::cerr<<"监听失败..."<<std::endl;
          break;
        default:
         for(int i=0;i<64;i++)
         {
           if(rfds[i].fd==-1)
           {
             continue;
           }

           if(rfds[i].fd==listen_sock&&rfds[i].revents==POLLIN)
           {
             struct sockaddr_in peer;
             socklen_t len=sizeof(peer);

             int sock=accept(listen_sock,(struct sockaddr*)&peer,&len);
             if(sock<0)
             {
               std::cerr<<"accept error"<<std::endl;
               break;
             }

             if(!Addrfds(rfds,sock,64))
             {
               close(sock);
               std::cerr<<"文件描述符满了，不在添加新的连接"<<std::endl;
               break;
             }
             std::cout<<"连接成功"<<":"<<"len"<<std::endl;
           }else if(rfds[i].revents==POLLIN)
           {
             char buffer[1024];
             ssize_t s=recv(rfds[i].fd,buffer,sizeof(buffer)-1,0);
             if(s<0)
             {
               close(rfds[i].fd);
               std::cerr<<"recv error"<<std::endl;
               rfds[i].fd=-1;
               rfds[i].events=0;
               rfds[i].revents=0;
             }else if(s>0)
             {
             buffer[s]=0;
             std::cout<<buffer<<std::endl;
             } else 
             {
               close(rfds[i].fd);
               std::cout<<"断开连接"<<std::endl;
               rfds[i].fd=-1;
               rfds[i].events=0;
               rfds[i].revents=0;
             }
           }
         }
          break;          
        }//end switch 
      }//end for 

      }
      bool Addrfds(struct pollfd rfds[],int sock,int size)
      {
        for(int i=0;i<size;i++)
        {
          if(rfds[i].fd==-1)
          {
            rfds[i].fd=sock;
            rfds[i].events |= POLLIN;
            //std::cout<<"sock"<<std::endl;
            return true;
          }
        }
        
          return false;
      }
  };
}
